<?php

namespace IDock\Insurance\AMIC;

use Exception;
use IDock\Http\Response;
use IDock\IDock\IDockInterface;
use IDock\Insurance\AMIC\Request\EPolicyDownloadRequest;
use IDock\Insurance\AMIC\Request\PolicyPaymentRequest;
use IDock\Insurance\AMIC\Request\PremiumInquiryRequest;
use IDock\Insurance\AMIC\Request\RenewalInquiryRequest;
use IDock\Insurance\AMIC\Request\UnderwritingRequest;
use IDock\Insurance\AMIC\Request\UploadFileRequest;
use IDock\Insurance\AMIC\Request\VehicleConfirmRequest;
use IDock\Insurance\AMIC\Request\VehicleModelRequest;
use IDock\Insurance\AMIC\Response\EPolicyDownloadResponse;
use IDock\Insurance\AMIC\Response\NonCarProductListResponse;
use IDock\Insurance\AMIC\Response\PolicyPaymentResponse;
use IDock\Insurance\AMIC\Response\PremiumInquiryResponse;
use IDock\Insurance\AMIC\Response\RenewalInquiryResponse;
use IDock\Insurance\AMIC\Response\UnderwritingResponse;
use IDock\Insurance\AMIC\Response\UploadFileResponse;
use IDock\Insurance\AMIC\Response\ValidateCarResponse;
use IDock\Insurance\AMIC\Response\VehicleActualValueResponse;
use IDock\Insurance\AMIC\Response\VehicleConfirmResponse;
use IDock\Insurance\AMIC\Response\VehicleModelResponse;
use IDock\Printer\NonCar\NonCarInquiryPrinter;
use IDock\Printer\NonCar\NonCarInquirySinglePrinter;
use IDock\Printer\VehicleActualValuePrinter;
use IDock\Visitor\EPolicyDownloadVisitor;
use IDock\Visitor\NonCar\NonCarInquiryVisitor;
use IDock\Visitor\NonCar\NonCarProductListVisitor;
use IDock\Visitor\NonCar\NonCarProductVisitor;
use IDock\Visitor\PolicyInfoVisitor;
use IDock\Visitor\PolicyPaymentVisitor;
use IDock\Visitor\Premium\PremiumInquiryVisitor;
use IDock\Visitor\ProposalRecallVisitor;
use IDock\Visitor\ProposalStatusVisitor;
use IDock\Visitor\RenewalInquiryVisitor;
use IDock\Visitor\UnderwritingRecallVisitor;
use IDock\Visitor\UploadFileVisitor;
use IDock\Visitor\ValidateCarVisitor;
use IDock\Visitor\VehicleActualValueVisitor;
use IDock\Visitor\VehicleModelVisitor;

/**
 * 珠峰保险
 */
class AMICConstruct extends Builder implements IDockInterface
{

    protected $config = [];

    public function __construct($config)
    {
        $this->config = $config;
        $this->channelName = $config['channelName'] ?? '';
        $this->appId = $config['appId'] ?? '';
        $this->appKey = $config['appKey'] ?? '';
        $this->planCodeNew = $config['planCodeNew'] ?? '';
    }

    /**
     * 车型查询
     * @param VehicleModelVisitor $vehicleModelVisitor
     * @return VehicleModelResponse
     */
    public function vehicleModel(VehicleModelVisitor $vehicleModelVisitor): VehicleModelResponse
    {
        $request = new VehicleModelRequest();
        $request->setVisitor($vehicleModelVisitor);

        $vehicleModelCode = explode('牌', $vehicleModelVisitor->vehicleModel);
        $vehicleModelCode = end($vehicleModelCode);

        $vehicleModelVisitor->argc['vehicleModelCode'] = $vehicleModelCode;

        /*** @var VehicleModelResponse $response */
        $response = $this->execute($request);

        //$response->filter($strEnd);
        return $response;
    }

    /**
     * 续保查询
     * @param RenewalInquiryVisitor $renewalInquiryVisitor
     * @return RenewalInquiryResponse
     * @version 4.0
     */
    public function renewalInquiry(RenewalInquiryVisitor $renewalInquiryVisitor): RenewalInquiryResponse
    {
        $request = new RenewalInquiryRequest();
        $request->setVisitor($renewalInquiryVisitor);
        /*** @var RenewalInquiryResponse $response */
        $response = $this->execute($request);
        return $response;
    }

    /**
     * 车辆实际价格接口
     * @param VehicleActualValueVisitor $vehicleActualValueVisitor
     * @return VehicleActualValueResponse
     */
    public function vehicleActualValue(VehicleActualValueVisitor $vehicleActualValueVisitor): VehicleActualValueResponse
    {
        $response = new VehicleActualValueResponse();
        $response->setCode('200');
        $vehicleActualValuePrinter = new VehicleActualValuePrinter();
        $response->printer = $vehicleActualValuePrinter;
        return $response;
    }

    /**
     * 询价前置
     * @param PremiumInquiryVisitor $premiumInquiryVisitor
     * @return RenewalInquiryResponse
     */
    public function preInquiry(PremiumInquiryVisitor $premiumInquiryVisitor): RenewalInquiryResponse
    {
        $visitor = new RenewalInquiryVisitor();
        $visitor->licenseNo = $premiumInquiryVisitor->getVehicleVisitor()->licenseNo;
        $visitor->vin = $premiumInquiryVisitor->getVehicleVisitor()->vin;
        $visitor->engineNo = $premiumInquiryVisitor->getVehicleVisitor()->engineNo;
        $visitor->argc = $premiumInquiryVisitor->getExtInfoVisitor()->argc;
        return $this->renewalInquiry($visitor);
    }

    public function validateCar(PremiumInquiryVisitor $premiumInquiryVisitor)
    {
    }

    /**
     * 询价
     * @param PremiumInquiryVisitor $premiumInquiryVisitor
     * @return Response|PremiumInquiryResponse
     * @throws Exception
     */
    public function premiumInquiry(PremiumInquiryVisitor $premiumInquiryVisitor)
    {
        //车型确认
        $request1 = new VehicleConfirmRequest();
        $request1->setVisitor($premiumInquiryVisitor);
        /**@var VehicleConfirmResponse $response * */
        $response1 = $this->execute($request1);
        if (!$response1->isSuccess()) {
            return $response1;
        }
        $model = $response1->printer->toArray();


        if (!$model) {
            throw new Exception('车型确认数据为空，请联系管理员');
        }

        if (count($model) == 1) {
            $model = $model[0];
        }else {
            $model = $this->modelMatch($model,$premiumInquiryVisitor->vehicleVisitor->vehiclePrice);
        }

        $premiumInquiryVisitor->vehicleVisitor->actualValue = $model['item']['actualPrice'] ?? '';
        $premiumInquiryVisitor->getExtInfoVisitor()->argc['vehiclePlatId'] = $model['item']['vehiclePlatId'] ?? '';
        $premiumInquiryVisitor->getExtInfoVisitor()->argc['vehicleStyleUniqueId'] = $model['item']['vehicleStyleUniqueId'] ?? '';
        $premiumInquiryVisitor->getExtInfoVisitor()->argc['vehiclePower'] = $model['item']['vehiclePower'] ?? '';
        $premiumInquiryVisitor->getExtInfoVisitor()->argc['vehicleExhaust'] = $model['item']['vehicleExhaust'] ?? '';
        $premiumInquiryVisitor->getExtInfoVisitor()->argc['vehicleCompleteKerbMass'] = $model['item']['vehicleCompleteKerbMass'] ?? '';
        $premiumInquiryVisitor->getExtInfoVisitor()->argc['vehicleLimitLoad'] = $model['item']['vehicleLimitLoad'] ?? '';

        //询价
        $request = new PremiumInquiryRequest();
        $request->setVisitor($premiumInquiryVisitor);

        /**@var PremiumInquiryResponse $response * */
        $response = $this->execute($request);
        if ($response->isSuccess()) {
            $response->buildCoverage($premiumInquiryVisitor->getVehicleVisitor()->isNewEnergy, $premiumInquiryVisitor->getCoverageVisitorList());
        }
        $nonCarInquiryPrinter = new NonCarInquiryPrinter();
        $totalPremium = 0;
        foreach ($premiumInquiryVisitor->getNonCarInquiryVisitor()->getNonCarList() as $item) {
            /*** @var $item NonCarProductVisitor */
            $single = new NonCarInquirySinglePrinter();
            $single->premium = $item->premium;
            $single->planCode = $item->planCode;
            $single->productCode = $item->productCode;
            $single->statusCode = 'success';
            $totalPremium += $single->premium * $item->insuredNum;
            $nonCarInquiryPrinter->noCarInquirySingleAppend($single);
        }
        $nonCarInquiryPrinter->totalPremium = $totalPremium;
        $response->printer->nonCarInquiryPrinter = $nonCarInquiryPrinter;
        return $response;
    }

    /**
     * 核保
     * @param PremiumInquiryVisitor $premiumInquiryVisitor
     * @return UnderwritingResponse
     */
    public function underwriting(PremiumInquiryVisitor $premiumInquiryVisitor): UnderwritingResponse
    {
        $request = new UnderwritingRequest();
        $request->setVisitor($premiumInquiryVisitor);
        /**@var UnderwritingResponse $response * */
        $response = $this->execute($request);
//        //非车数据回填重构
//        /*** @var PremiumUnderwritingPrinter $printer */
//        $printer = $response->getPrinter();
//        if ($printer->noCarUnderwritingPrinter->statusCode == 'success' && !empty($premiumInquiryVisitor->getNonCarUnderwritingVisitor()->getNonCarList())) {
//
//            /*** @var NonCarProductVisitor $nonProduct */
//            $nonProduct = $premiumInquiryVisitor->getNonCarUnderwritingVisitor()->getNonCarList()[0];
//
//            $nonCarList = $printer->noCarUnderwritingPrinter->getNonCarInquiryList();
//
//            foreach ($nonCarList as &$value) {
//                /*** @var NonCarInquirySinglePrinter $value */
//                $value->productCode = $nonProduct->productCode;
//                $value->planCode = $nonProduct->planCode;
//            }
//        }

//        $response->printer = $printer;
        return $response;
    }

    /**
     * 获取支付链接
     * @param PolicyPaymentVisitor $paymentVisitor
     * @return PolicyPaymentResponse
     */
    public function policyPayment(PolicyPaymentVisitor $paymentVisitor): PolicyPaymentResponse
    {
        $request = new PolicyPaymentRequest();
        $request->setVisitor($paymentVisitor);

        /**@var PolicyPaymentResponse $response * */
        $response = $this->execute($request);

        return $response;
    }

    public function proposalStatus(ProposalStatusVisitor $proposalStatusVisitor)
    {
    }

    public function proposalRecall(ProposalRecallVisitor $revokeVisitor)
    {
    }

    /**
     * 撤单接口
     * @param UnderwritingRecallVisitor $recallVisitor
     */
    public function underwritingRecall(UnderwritingRecallVisitor $recallVisitor)
    {
    }

    public function EPolicyDownload(EPolicyDownloadVisitor $EPolicyVisitor): EPolicyDownloadResponse
    {
        $request = new EPolicyDownloadRequest();
        $request->setVisitor($EPolicyVisitor);

        /*** @var EPolicyDownloadResponse $response */
        $response = $this->execute($request);
        return $response;
    }

    public function policyInfo(PolicyInfoVisitor $policyInfoVisitor)
    {
    }

    /**
     * @param UploadFileVisitor $uploadFileVisitor
     * @return UploadFileResponse
     * @throws Exception
     */
    public function UploadFile(UploadFileVisitor $uploadFileVisitor): UploadFileResponse
    {
        $request = new UploadFileRequest();
        $list = $uploadFileVisitor->fileList;
        $request->setVisitor($uploadFileVisitor);
        if (empty($list)) {
            throw new Exception("图片不能为空");
        }
        /*** @var UploadFileResponse $response */
        $response = $this->execute($request);
        return $response;
    }


    /**
     * 非车产品列表
     * @param NonCarProductListVisitor $nonCarProductListVisitor
     * @return NonCarProductListResponse
     * @version 4.0
     */
    public function nonCarProductList(NonCarProductListVisitor $nonCarProductListVisitor): NonCarProductListResponse
    {
        $response = new NonCarProductListResponse(200);
        $response->printerInit();
        return $response;
    }

    public function nonCarInquiry(NonCarInquiryVisitor $nonCarInquiryVisitor)
    {
    }

    public function nonCarUnderwriting(NonCarInquiryVisitor $inquiryPrinter)
    {
    }

    /**
     * 验车码接口
     * @param ValidateCarVisitor $validateCarVisitor
     * @return ValidateCarResponse
     */
    public function validateCarCode(ValidateCarVisitor $validateCarVisitor): ValidateCarResponse
    {
        $response = new ValidateCarResponse(200);
        $response->printerInit();
        return $response;
    }

    /**
     * 新车备案
     * @return void
     */
    public function newVehicleRegistration(PremiumInquiryVisitor $premiumInquiryVisitor)
    {
    }


    /**
     * 车型匹配
     * @param $modelList
     * @param $vehiclePrice
     * @return array
     */
    private function modelMatch($modelList,$vehiclePrice) :array
    {
        //全等价
        foreach ($modelList as &$value) {
            if ($value['item']['vehiclePrice'] == $vehiclePrice) {
                return  $value;
            } else {
                $value['diffPrice'] = abs($vehiclePrice-$value['item']['vehiclePrice']);
            }
        }
        //非全等价
        usort($modelList,function ($a,$b) {
            return $a['diffPrice'] > $b['diffPrice'];
        });

        return $modelList[0];
    }
}
